package cc.cix.gt.common.util;

import cc.cix.gt.common.properties.JwtSecurityProperties;
import cc.cix.gt.org.entity.User;
import cc.cix.gt.org.mapper.UserMapper;
import cn.hutool.core.util.ObjectUtil;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author cix
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtTokenUtil implements InitializingBean {

    private final static String AUTHORITIES_KEY = "auth";

    private final JwtSecurityProperties jwtSecurityProperties;
    private final UserMapper userMapper;

    private Key key;

    @Override
    public void afterPropertiesSet() {
        byte[] keyBytes = Decoders.BASE64.decode(jwtSecurityProperties.getBase64Secret());
        key = Keys.hmacShaKeyFor(keyBytes);
    }

    /**
     * 创建 token
     *
     * @param userId 用户id
     * @param auths  权限集合
     * @return String token
     */
    public String createToken(String userId, List<String> auths) {
        return Jwts.builder()
                .setSubject(userId)
                .claim(AUTHORITIES_KEY, auths)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date())
                .setExpiration(new Date((new Date()).getTime() +
                        jwtSecurityProperties.getTokenValidityInSeconds()))
                .compressWith(CompressionCodecs.DEFLATE)
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
    }

    public Authentication getAuthentication(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();

        if (ObjectUtil.isNotNull(claims.get(AUTHORITIES_KEY))) {
            List<String> auths = (List<String>) claims.get(AUTHORITIES_KEY);
            List<SimpleGrantedAuthority> authorities = auths.stream()
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
            String userId = claims.getSubject();
            User user = userMapper.selectById(userId);
            return new UsernamePasswordAuthenticationToken(user, token, authorities);
        } else {
            return null;
        }
    }

    public boolean validateToken(String authToken) {
        try {
            Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(authToken);
            return true;
        } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
            log.info("Invalid JWT signature.");
            e.printStackTrace();
        } catch (ExpiredJwtException e) {
            log.info("Expired JWT token.");
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            log.info("Unsupported JWT token.");
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            log.info("JWT token compact of handler are invalid.");
            e.printStackTrace();
        }
        return false;
    }

}
